import { Inject } from '@midwayjs/core';
// import { BaseEntity } from './base.entity';
import { Context } from '@midwayjs/koa';
import { FindOptionsWhere } from 'typeorm';

export abstract class BaseService<T> {
  @Inject()
  protected ctx: Context;

  // protected abstract model: Repository<T>;
  protected abstract model;

  // 新增
  async create(entity: T) {
    return await this.model.save(entity);
  }

  // 删除
  async delete(id: number) {
    return await this.model.delete(id);
  }

  // 修改
  async update(entity: T): Promise<T | void> {
    return await this.model.save(entity);
  }

  // 根据条件返回
  async findBy(where: FindOptionsWhere<T>): Promise<T> {
    return this.model.findOneBy(where);
  }

  // 分页查询
  async findAndCount(
    offset: number,
    limit: number,
    where?: FindOptionsWhere<T>
  ) {
    const order: any = { create_time: 'desc' };
    return await this.model.findAndCount({
      where,
      order,
      skip: offset,
      take: limit,
    });
    // return { data, total, offset, limit };
  }

  // 根据查询条件返回全部
  async list(where?: FindOptionsWhere<T>) {
    const order: any = { create_time: 'desc' };
    const data = await this.model.find({
      where,
      order,
    });
    return data;
  }
}
